/**
 * 处理错误,抛出的错误，在这里处理
 */

const errorTypes = require("../constans/error-types");

const errorHandler = (error, ctx) => {
  let status, message;
  switch (error.message) {
    case errorTypes.NAME_OR_PASSWORD_IS_REQUIRED:
      status = 400; //Bad Request  请求错误，参数不对
      message = errorTypes.NAME_OR_PASSWORD_IS_REQUIRED;
      break;
    case errorTypes.USER_ALREADY_EXISTS:
      status = 409; //conflict  冲突
      message = errorTypes.USER_ALREADY_EXISTS;
      break;
    case errorTypes.USER_NOT_EXISTS:
      status = 400; //参数错误
      message = errorTypes.USER_NOT_EXISTS;
      break;
    case errorTypes.PASSWORD_IS_INCORRENT:
      status = 400; //参数错误
      message = errorTypes.PASSWORD_IS_INCORRENT;
      break;
    case errorTypes.UNAUTHORIZATION:
      status = 401;
      message = errorTypes.UNAUTHORIZATION;
      break;
    case errorTypes.UNPERMISSION:
      status = 401;
      message = errorTypes.UNPERMISSION;
      break;
    case errorTypes.NOPARAMETER:
      status = 400;
      message = errorTypes.NOPARAMETER;
      break;
    case errorTypes.PARAMETER_ERROR:
      status = 422;
      message = errorTypes.PARAMETER_ERROR;
      break;
    default:
      status = 404;
      message = "NOT FOUND";
  }

  ctx.status = status;
  ctx.body = {
    code: status,
    msg: "error",
    data: message,
  };
};

module.exports = errorHandler;
